package com.cloudlead.common.worker.web;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudlead.common.lang.api.ActionResponse.Level;
import com.cloudlead.common.lang.api.SimpleActionResponse;
import com.fasterxml.jackson.databind.JsonMappingException;

/**
 * Implementation if {@link ExceptionMapper} to send down a "400 Bad Request"
 * response in the event that unmappable JSON is received.
 */
@Provider
public class JsonMappingExceptionMapper implements
		ExceptionMapper<JsonMappingException> {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(JsonMappingExceptionMapper.class);

	@Override
	public Response toResponse(JsonMappingException ex) {
		LOGGER.error("json mapping error", ex);

		SimpleActionResponse<String> result = new SimpleActionResponse<>(false,
				Level.error, ex.getMessage(),
				Response.Status.BAD_REQUEST.getStatusCode(),
				ex.getMessage());
		return Response.ok().entity(result)
				.type(MediaType.APPLICATION_JSON).build();
	}

}